// 购物车模块
import {getCartListAPI} from '@/api/cartAPI.js'
const moduleCart = {
  namespaced: true,
  state() {
    return {
      cartlist: []
    }
   },
  actions: {
    async initCartList(ctx) {
      const { data: res } = await getCartListAPI()
      if (res.status === 200) {
        ctx.commit('updateCartList',res.list)
      }
   }
  },
  mutations: {
    updateCartList(state, payload) {
      state.cartlist = payload
    },
    updateGoodsState(state, payload) {
      state.cartlist.some(x => {
        if (x.id === payload.id) {
          x.goods_state = payload.value
          return true
        }
      })
    },
    updateGoodsCount(state, payload) {
      state.cartlist.some(x => {
        if (x.id === payload.id) {
          x.goods_count = payload.value
          return true
       }
     })
    },
    updateAllGoodsState(state, payload) {
      state.cartlist.forEach(x => {
        x.goods_state = payload.value
      })
    }
  },
  getters: {
    isFullCheck(state) {
      return state.cartlist.every(item => item.goods_state)
    },
    amount(state) {
      let amt = 0
      state.cartlist
        .filter(x => x.goods_state)
        .forEach(x => {
        amt += x.goods_count * x.goods_price
        })
      return amt
    },
    total(state) {
      let t = 0
      state.cartlist.filter(x => x.goods_state).forEach(x => {
        t += x.goods_count
      })
      return t
    }
  }
}
export default moduleCart
